package com.example.cipher.sm4;

import org.bouncycastle.util.encoders.Hex;

import javax.xml.bind.DatatypeConverter;

public class SM4Utils {

    /**
     * SM4加密
     * @param str 参数
     * @param key 随机码
     * @return
     */
    public static String EncryptStr(String str,String key) {
        return DatatypeConverter.printHexBinary(new SM4_Context().EncryptByte(str.getBytes(),key.getBytes()));
    }
    /**
     * 解密
     * @param cipherStrings  密文
     * @param keyStr    随机码
     * @return
     */
    public static String DecryptStr(String cipherStrings,String keyStr) {
        String result = "";
        SM4_Context aa=new SM4_Context();
        byte[] cc="00".getBytes();
        byte[] dd="00".getBytes();

        byte[] cipherText = Hex.decode(cipherStrings);
        byte[] keyBytes = keyStr.getBytes();

        try {

            dd= aa.DecryptStrByte(cipherText,keyBytes);
            result = new String(dd);
        } catch (Exception e) {
        }
        return result;

    }


    public static void main(String[] args) {
        //参数
        String str = "{\"test\":\"001\"}";
        System.out.println("参数:" + str);
        //key必须是16位
        String key ="LSxH5p1vs3ePYJfM";
        String ncECBData = EncryptStr(str, key);
        System.out.println("加密:"+ncECBData);
        String plainTextEncripted = DecryptStr(ncECBData,key);
        System.out.println("解密:"+plainTextEncripted);
    }
}